import { API } from "../../utils/network/api";
import { httpRequest } from "../../utils/network/network";

const app = getApp();

Component({

  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    loginStatus: false,
    phoneNumber: "",
    userName: "",
    verifyMsg: ""
  },
  /**
   * 组件的方法列表
   */
  methods: {
    initPopup(val) {
      this.setData({
        loginStatus: val
      })
    },
    onClose() {
      this.setData({
        loginStatus: false
      });
      this.triggerEvent("cancel", { show: this.data.loginStatus });
    },
    async login() {
      if (!this.data.phoneNumber) {
        this.setData({
          verifyMsg: "请输入手机号"
        })
        return;
      }
      if (this.data.phoneNumber.length != 11) {
        this.setData({
          verifyMsg: "请输入11位手机号"
        })
        return;
      }
      // clear verify msg
      this.setData({
        verifyMsg: ""
      })
      const params = {
        userName: this.data.userName ? this.data.userName : "微信用户",
        phoneNumber: this.data.phoneNumber
      }
      // login
      const res = await httpRequest(API.login, params, "POST");
      wx.setStorageSync("token", res.data.token);
      wx.setStorageSync("userId", res.data.userId);
      wx.setStorageSync("loginStatus", true);
      app.globalData.loginStatus = true;
      this.triggerEvent("success", res);

      this.setData({
        phoneNumber: ""
      })
    }
  },
  observers: {
    show: function (val) {
      this.initPopup(val);
    }
  }
})